package com.han.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JWTUtil {
    private static final long EXPIRE_TIME = 30*60*1000;
    private static final String screct="wqw123";
    private static final Algorithm algorithm = Algorithm.HMAC256(screct);

    /**
     * 生成签名，30min后过期
     * @param sid
     * @return
     */
    public static String sign(String sid){
        Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
        //附带sid信息
        return JWT.create()
                .withClaim("sid",sid)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * 验证token是否正确
     * @param token
     * @return
     */
    public static boolean verify(String token){
        DecodedJWT jwt = null;
        try{
            JWTVerifier verifier = JWT.require(algorithm).build();
            jwt = verifier.verify(token);
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取token中一些信息值
     * @param token
     * @param name
     * @return
     */
    public static String getClaimByName(String token,String name){
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim(name).asString();
    }
}
